<template>
  <div class="list-common-table">
    <t-divider>年龄查询</t-divider>
    <t-form
      ref="form"
      :data="formData"
      :label-width="80"
      colon
      :style="{ marginBottom: '8px' }"
      @reset="onReset"
      @submit="onSubmit"
    >
      <t-row>
        <t-col :span="10">
          <t-row :gutter="[16, 24]">
            <t-col :span="4">
              <t-form-item label="查询" name="type">
                <t-input
                  v-model="formData.type"
                  style="display: inline-block"
                  class="form-item-content"
                  placeholder="请输入想要查询的年龄，返回大于该年龄的顾客信息"
                />
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>

        <t-col :span="2" class="operation-container">
          <t-button theme="primary" type="submit" :style="{ marginLeft: '8px' }"> 查询 </t-button>
          <t-button type="reset" variant="base" theme="default"> 重置 </t-button>
          <t-button theme="primary" variant="outline" @click="btnclick"> 一键删除小于18 </t-button>
        </t-col>
      </t-row>
    </t-form>

    <div class="table-container">
      <t-table
        :data="data"
        :columns="COLUMNS"
        :row-key="rowKey"
        :vertical-align="verticalAlign"
        :hover="hover"
        :pagination="pagination"
        :loading="dataLoading"
        :header-affixed-top="{ offsetTop, container: getContainer }"
        @page-change="rehandlePageChange"
        @change="rehandleChange"
      >
        <template #fitStatus="{ row }">
          <t-tag v-if="row.fitStatus === 'very fit'" theme="success" variant="light"> 非常健康 </t-tag>
          <t-tag v-if="row.fitStatus === 'moderately fit'" theme="warning" variant="light"> 一般健康 </t-tag>
          <t-tag v-if="row.fitStatus === 'not fit'" theme="danger" variant="light"> 不健康 </t-tag>
        </template>
        <template #op="slotProps">
          <a class="t-button-link" @click="rehandleClickOp(slotProps)">管理</a>
          <a class="t-button-link" @click="handleClickDelete(slotProps)">删除</a>
        </template>
      </t-table>
      <t-dialog
        v-model:visible="confirmVisible"
        header="确认删除当前所选合同？"
        :body="confirmBody"
        :on-cancel="onCancel"
        @confirm="onConfirmDelete"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { MessagePlugin, NotifyPlugin } from 'tdesign-vue-next';
import { Axis } from 'echarts/core';
import axios from 'axios';
import Trend from '@/components/trend/index.vue';
import { getList } from '@/api/list';
import { useSettingStore } from '@/store';
import { prefix } from '@/config/global';

import {
  CONTRACT_STATUS,
  CONTRACT_STATUS_OPTIONS,
  CONTRACT_TYPES,
  CONTRACT_TYPE_OPTIONS,
  CONTRACT_PAYMENT_TYPES,
} from '@/constants';

// 删除小于18
function btnclick() {
  axios
    .get(`http://127.0.0.1:8080/removeLess18`)
    .then((res) => {
      console.log(res.data);
    })
    .catch((e) => {
      console.log(e);
      NotifyPlugin.error({
        placement: 'bottom-right',
        title: '删除异常',
        content: '已经没有小于18岁的顾客了',
        duration: 3000,
      });
    });
}

const store = useSettingStore();

const COLUMNS = [
  {
    title: '顾客ID',
    fixed: 'left',
    width: 200,
    ellipsis: true,
    align: 'left',
    colKey: 'customerId',
  },
  { title: '顾客的姓', colKey: 'firstName', width: 200, cell: { col: 'status' } },
  {
    title: '顾客的名',
    width: 200,
    ellipsis: true,
    colKey: 'lastName',
  },
  {
    title: '电子邮箱',
    width: 200,
    ellipsis: true,
    colKey: 'email',
  },
  {
    title: '健康状态',
    width: 200,
    ellipsis: true,
    colKey: 'fitStatus',
  },
  {
    title: '出生日期',
    width: 200,
    ellipsis: true,
    colKey: 'birthDate',
  },
  {
    align: 'left',
    fixed: 'right',
    width: 200,
    colKey: 'op',
    title: '操作',
  },
];

const searchForm = {
  name: '',
  no: undefined,
  status: undefined,
  type: '',
};

const formData = ref({ ...searchForm });
const rowKey = 'index';
const verticalAlign = 'top';
const hover = true;

const pagination = ref({
  defaultPageSize: 20,
  total: 100,
  defaultCurrent: 1,
});
const confirmVisible = ref(false);

const data = ref([]);

const dataLoading = ref(false);
const fetchData = async () => {
  dataLoading.value = true;
  try {
    const { list } = await getList();
    console.log(list);
    data.value = list;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};

onMounted(() => {
  const age = 0;
  axios
    .get(`http://127.0.0.1:8080/overAge?age=${age}`)
    .then((res) => {
      console.log(res.data);
      const list = res.data;
      data.value = list;
      pagination.value = {
        ...pagination.value,
        total: list.length,
      };
    })
    .catch((e) => {
      console.log(e);
    });
});

const deleteIdx = ref(-1);
const confirmBody = computed(() => {
  if (deleteIdx.value > -1) {
    const { name } = data.value[deleteIdx.value];
    return `删除后，${name}的所有合同信息将被清空，且无法恢复`;
  }
  return '';
});

const resetIdx = () => {
  deleteIdx.value = -1;
};

const onConfirmDelete = () => {
  // 真实业务请发起请求
  data.value.splice(deleteIdx.value, 1);
  pagination.value.total = data.value.length;
  confirmVisible.value = false;
  MessagePlugin.success('删除成功');
  resetIdx();
};

const onCancel = () => {
  resetIdx();
};

const handleClickDelete = ({ row }) => {
  deleteIdx.value = row.rowIndex;
  confirmVisible.value = true;
};
const onReset = (val) => {
  console.log(val);
};

// 点击事件
const onSubmit = () => {
  console.log(formData.value.type);
  const age = formData.value.type;
  axios
    .get(`http://127.0.0.1:8080/overAge?age=${age}`)
    .then((res) => {
      console.log(res.data);
      const list = res.data;
      data.value = list;
      pagination.value = {
        ...pagination.value,
        total: list.length,
      };
    })
    .catch((e) => {
      console.log(e);
      NotifyPlugin.error({
        placement: 'bottom-right',
        title: '查询异常',
        content: '没有符合该条件的结果，请重试',
        duration: 3000,
      });
    });
};
const rehandlePageChange = (curr, pageInfo) => {
  console.log('分页变化', curr, pageInfo);
};
const rehandleChange = (changeParams, triggerAndData) => {
  console.log('统一Change', changeParams, triggerAndData);
};
const rehandleClickOp = ({ text, row }) => {
  console.log(text, row);
};

const offsetTop = computed(() => {
  return store.isUseTabsRouter ? 48 : 0;
});

const getContainer = () => {
  return document.querySelector(`.${prefix}-layout`);
};
</script>

<style lang="less" scoped>
.list-common-table {
  background-color: var(--td-bg-color-container);
  padding: 30px 32px;
  border-radius: var(--td-radius-default);

  .table-container {
    margin-top: 30px;
  }
}

.form-item-content {
  width: 100%;
}

.operation-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  .expand {
    .t-button__text {
      display: flex;
      align-items: center;
    }
    .t-icon {
      margin-left: 4px;
      transition: transform 0.3s ease;
    }
  }
}

.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: 8px;
  }
}
</style>
